// Start with
// http://www.arduino.cc/en/Tutorial/SPIEEPROM

#define DATAOUT 11//MOSI
#define DATAIN  12//MISO 
#define SPICLOCK  13//sck
#define SLAVESELECT 10//ss

int sensorPin = A7;    // select the input pin
boolean use_test_data = false;
int test_data_count = 0;

char spi_transfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1<<SPIF)))     // Wait the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}

void write_register(byte addr, int data) {
  digitalWrite(SLAVESELECT,LOW);
  spi_transfer(B00000000);   // Write access
  spi_transfer(addr);
  spi_transfer((data>>8)&0xFF ); //write data byte
  spi_transfer(data&0xFF);       //write data byte
  digitalWrite(SLAVESELECT,HIGH); //release chip, signal end transfer
}

unsigned int read_register(byte addr)
{
  byte data0, data1;
  digitalWrite(SLAVESELECT,LOW);
  spi_transfer(B10000000);   // Read access
  spi_transfer(addr); // Register 6 should contain 0xAB05
  data0 = spi_transfer(0xFF); //get data byte
  data1 = spi_transfer(0xFF); //get data byte
  digitalWrite(SLAVESELECT,HIGH); //release chip, signal end transfer
  return (data0<<8) + data1;
}

void send_registers() {
  int i;
  for (i=0; i<32; i++) {
    Serial.print(read_register(i),HEX);
    Serial.print(" ");
  }
  Serial.print(analogRead(sensorPin),HEX);
  Serial.print('\n',BYTE);//debug
}

void send_test_data() {
  int i;
  Serial.print("FF08 E078 0 0 0 ");
  // Serial.print("EAB");
  Serial.print(random(3795,4000),HEX);
  Serial.print(" AB05 B0 ");
  for (i=0; i<24; i++) {
    Serial.print(test_data_count + i,HEX);
    Serial.print(" ");
  }
  test_data_count++;
  test_data_count %= 64;
  Serial.print('\n',BYTE);//debug
}

void setup()
{
  byte clr;
  Serial.begin(9600);

  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK,OUTPUT);
  pinMode(SLAVESELECT,OUTPUT);
  digitalWrite(SLAVESELECT,HIGH); //disable device
  // SPCR = 01010000
  //interrupt disabled,spi enabled,msb 1st,master,clk low when idle,
  //sample on leading edge of clk,system clock/4 rate (fastest)
  SPCR = (1<<SPE)|(0<<DORD)|(1<<MSTR)|(0<<CPOL)|(1<<CPHA)|(1<<SPR1)|(1<<SPR0);
  clr=SPSR;
  clr=SPDR;
  delay(100);
  Serial.print("Ready\n");
}

void loop()
{
  byte inByte;
  if (Serial.available() > 0) {
    inByte = Serial.read();
    switch (inByte) {
      case 'G':
        if (use_test_data)
          send_test_data();
        else
          send_registers();
        break;
      case 'T':
        Serial.write("Test response 11/9/10b\n");
        break;
      case 't':
        use_test_data = !use_test_data;
        break;
      case 'W':
        delay(100);
        inByte = Serial.read();
        Serial.write("Writing in register 3: ");
        Serial.print(inByte,HEX);
        Serial.write('\n');
        write_register(3,inByte);
        break;
    }
  }
}
